import axios from 'axios';
import {ElMessage} from "element-plus";
import {formatDate} from "./Utils.js";

// 开发环境使用代理，生产环境使用完整地址
const basePath = import.meta.env.DEV ? '' : import.meta.env.VITE_BACKEND_BASE_URL;

async function loadEntityBase(entityPath, id) {
    try {
        let {data} = await axios(basePath + entityPath + "/" + id);
        if (data.code === '1') {
            return data.data;
        } else {
            ElMessage.error(data.msg)
        }
    } catch (error) {
        console.log(error);
    }
}

async function loadAllBase(entityPath) {
    try {
        let {data} = await axios(basePath + entityPath);
        if (data.code === '1') {
            return data.data;
        } else {
            ElMessage.error(data.msg)
        }
    } catch (error) {
        console.log(error);
    }
}

async function pageListBase(entityPath, paginationDTO) {
    try {
        if (paginationDTO.condition != null) {
            for (const key in paginationDTO.condition) {
                if (paginationDTO.condition.hasOwnProperty(key) && (key.includes("time") || key.includes("Time")) && paginationDTO.condition[key] instanceof Date) {
                    paginationDTO.condition[key] = formatDate(paginationDTO.condition[key])
                }
            }
        }
        let {data} = await axios.post(basePath + entityPath + "/pageList", paginationDTO);
        if (data.code === '1') {
            return data.data;
        } else {
            ElMessage.error(data.msg)
        }
    } catch (error) {
        console.log(error);
    }
}

async function createEntityBase(entityPath, entity) {
    try {
        let {data} = await axios.post(basePath + entityPath, entity);
        if (data.code === '1') {
            return data.data;
        } else {
            ElMessage.error(data.msg)
        }
    } catch (error) {
        console.log(error);
    }
}

async function updateEntityBase(entityPath, id, entity) {
    try {
        let {data} = await axios.put(basePath + entityPath + "/" + id, entity);
        if (data.code === '1') {
            return data.data;
        } else {
            ElMessage.error(data.msg)
        }
    } catch (error) {
        console.log(error);
    }
}

async function removeEntityBase(entityPath, id) {
    try {
        let {data} = await axios(basePath + entityPath + "/" + id);
        if (data.code === '1') {
            return data.data;
        } else {
            ElMessage.error(data.msg)
        }
    } catch (error) {
        console.log(error);
    }
}

export {loadEntityBase, loadAllBase, pageListBase, createEntityBase, updateEntityBase, removeEntityBase};

